<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\User;

class TeamLog extends \Service\Common\BaseModel
{
    protected $name = 'team_log';

    const TYPE_CONTRIBUTION = 0;//贡献

    //团队贡献
    public function addTeamContribution($uid, $order)
    {
        //业绩记录
        $this->_add($uid, $order['id'], $order['uid'], $order['order_contribution'], self::TYPE_CONTRIBUTION);
        //累计贡献
        $update = M('user')->where(['uid' => $uid])->save([
            'total_contribution' => ['exp', "total_contribution+{$order['order_contribution']}"]
        ]);
        if ($update === false) {
            throw new \Exception("团队业绩累计失败");
        }
        //升级管理级别
        //OE('user')->upgradeManageLevel($uid);
        return;
    }

    protected function _add($uid, $order_id, $order_uid, $performance, $type)
    {
        $insert_id = M('team_log')->add([
            'create_time' => date('Y-m-d H:i:s'),
            'uid' => $uid,
            'order_id' => $order_id,
            'order_uid' => $order_uid,
            'performance' => $performance,
            'type' => $type,
        ]);
        if (!$insert_id) {
            throw new \Exception("团队业绩插入失败");
        }
        return $insert_id;
    }

    //获取业绩统计
    public function getUserTeamInfo($login_info)
    {
        $total_month_contribution = $this->where(['uid' => $login_info['uid'], 'create_time' => ['egt', date('Y-m-01')]])->sum('performance');
        $total_today_contribution = $this->where(['uid' => $login_info['uid'], 'create_time' => ['egt', date('Y-m-d')]])->sum('performance');
        return [
            get_decimal($login_info['total_contribution']),
            get_decimal($total_month_contribution),
            get_decimal($total_today_contribution),
        ];
    }
}